package com.tian.consumer;

import com.rabbitmq.client.Channel;
import com.tian.dto.UserPointDto;
import com.tian.enums.ResultCode;
import com.tian.feign.UserPointFeignClient;
import com.tian.util.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年05月14日 22:22
 * 博客地址：<a href="http://woaijava.cc/">博客地址</a>
 * <p>
 * <p>
 * 异步操作用户积分---初始化积分账户、积分变更（增加积分、扣减积分）
 */
@Slf4j
@Component
public class UserPointConsumer {

    @Resource
    private UserPointFeignClient userPointFeignClient;

    @RabbitListener(queues = {"${rabbitmq.point.init.message.queue.name}"})
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println(new String(message.getBody()));
            UserPointDto userPointDto = new UserPointDto();
            CommonResult<Boolean> commonResult = userPointFeignClient.init(userPointDto);
            if (commonResult.getCode() == ResultCode.SUCCESS.getCode()) {
                //正常消费完成ack掉
                channel.basicAck(deliveryTag, true);
            } else {
                log.error("积分初始化失败");
                //需要再次投递消息
                channel.basicNack(deliveryTag, true, true);
            }
        } catch (Exception e) {
            log.error("积分初始化失败：", e);
            //需要再次投递消息
            channel.basicNack(deliveryTag, true, true);
        }
    }
}


